package com.hewanglan.wx.handler;

import com.hewanglan.wx.redis.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class ReceiveTextMsgHandler implements WxChatMsgHandler{

    private static final String KEY_WORD="验证码";
    private static final String LOGIN_PREFIX="loginCode";
    @Resource
    private RedisUtil redisUtil;
    @Override
    public WxChatMsgTypeEnum getMsgType() {
        return WxChatMsgTypeEnum.TEXT_MSG;
    }

    @Override
    public String dealMsg(Map<String, String> messageMap) {
        log.info("触发接收用户文本消息事件！");
        String content=messageMap.get("Content");
        if(!content.equals(KEY_WORD))
        {
            return "";
        }
        String fromUserName = messageMap.get("FromUserName"); //用户
        String toUserName = messageMap.get("ToUserName");       //公众号
        //生成四位验证码
        Random random=new Random();
        int num= random.nextInt(10000);
        //将验证码保存到缓存中，并设置验证码有效期为5分钟
        String numKey = redisUtil.buildKey(LOGIN_PREFIX,String.valueOf(num));
        redisUtil.setNx(numKey,fromUserName, Long.valueOf(5), TimeUnit.MINUTES);

        String res_data="您当前的验证码是:"+num+" 【5分钟内有效】";
        String replyContent = "<xml>\n" +
                "  <ToUserName><![CDATA[" + fromUserName + "]]></ToUserName>\n" +
                "  <FromUserName><![CDATA[" + toUserName + "]]></FromUserName>\n" +
                "  <CreateTime>12345678</CreateTime>\n" +
                "  <MsgType><![CDATA[text]]></MsgType>\n" +
                "  <Content><![CDATA[" + res_data + "]]></Content>\n" +
                "</xml>";
        return replyContent;
    }


}
